<?php
namespace common\component\aliyun;

use Yii;
use common\component\tool\Tool;
use common\component\tool\HttpClient;
use common\component\exception\ErrMap;

/*
阿里云 sts类
参考 https://www.cnblogs.com/llkbk/p/12166501.html
*/
class Sts extends Ali
{

    public $accessKeyId;
    public $accessKeySecret;
    public $stsUrl;
    public $accountID;
    public $roleName;

    public function __construct($accessKeyId, $accessKeySecret, $stsUrl, $accountID, $roleName)
    {
        $this->accessKeyId = $accessKeyId;
        $this->accessKeySecret = $accessKeySecret;
        $this->stsUrl = $stsUrl;
        $this->accountID = $accountID;
        $this->roleName = $roleName;
    }

    /*sts 获取临时身份*/
    public function getSts()
    {
        $httpClient = new HttpClient($this->stsUrl);
        // $httpClient->url = '/basic/open-app';
        $httpClient->data = [
            'Action' => 'AssumeRole',
            'Format' => 'JSON',
            'Version' => '2015-04-01',
            // 'Signature' => '',
            'SignatureMethod' => 'HMAC-SHA1',
            'SignatureNonce' => Tool::generateRandomStr(10, 'num'),
            'SignatureVersion' => '1.0',
            'AccessKeyId' => $this->accessKeyId,
            'Timestamp' => gmdate("Y-m-d\TH:i:s\Z", time()),
            'RoleArn' => 'acs:ram::' . $this->accountID . ':role/' . $this->roleName,//指定角色的ARN
            'RoleSessionName' => 'alice',//用户自定义参数
            // 'Policy' => '',//权限策略
            // 'DurationSeconds' => '',//过期时间，单位为秒 默认3600秒
        ];
        // P($httpClient->data);
        $signature = $this->computeSignature($httpClient->data, $this->accessKeySecret);

        $httpClient->data['Signature'] = $signature;
        // P($httpClient->data);
        if($res = $httpClient->get()){
            // P($res);
            return Tool::showRes([0, '获取成功'], $res);
        }
    }

    /*获取STS签名*/

    private function computeSignature($parameters, $accessKeySecret)
    {
        // 将参数Key按字典顺序排序
        ksort($parameters);
        // 生成规范化请求字符串
        $canonicalizedQueryString = '';
        foreach($parameters as $key => $value)
        {
            $canonicalizedQueryString .= '&' . $this->percentEncode($key)
                . '=' . $this->percentEncode($value);
        }
        // 生成用于计算签名的字符串 stringToSign
        $stringToSign = 'GET&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));
        // 计算签名，注意accessKeySecret后面要加上字符'&'
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));
        return $signature;
    }

    private function percentEncode($str)
    {
        // 使用urlencode编码后，将"+","*","%7E"做替换即满足ECS API规定的编码规范
        $res = urlencode($str);
        $res = preg_replace('/\+/', '%20', $res);
        $res = preg_replace('/\*/', '%2A', $res);
        $res = preg_replace('/%7E/', '~', $res);
        return $res;
    }


}